/*
 * Copyright 2009 Colin Prinn
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

package net.recursv.motific.at.utils;

import java.util.Enumeration;
import java.util.Hashtable;

/**
 * Created by: recursv
 * Date: 10/08/2009
 * Time: 12:01:09 PM
 */
public class KeyMap {
    private static Hashtable _map;

    /**
     * @param value the name of the key code
     * @return the key code or -1 if not found
     */
    public static int getKeyCode(String value) {
        if (_map == null) {
            throw new RuntimeException("KeyMap uninitialised");
        } else {
            return _map.containsKey(value) ? ((Integer) _map.get(value)).intValue() : -1;
        }
    }

    /**
     * @param value the name of the key code
     * @return the key code or -1 if not found
     */
    public static int getKeyCode(char value) {
        return getKeyCode(String.valueOf(value));
    }

    /**
     * Return the string representation of a key code
     *
     * @param keyCode the key code
     * @return the name
     */
    public static String getKeyString(int keyCode) {
        if (_map == null) {
            throw new RuntimeException("KeyMap uninitialised");
        } else {
            Enumeration keys = _map.keys();
            while (keys.hasMoreElements()) {
                String name = (String) keys.nextElement();
                Integer code = (Integer) _map.get(name);
                if (code.intValue() == keyCode) {
                    return name;
                }
            }
            return "UNKNOWN KEY: " + keyCode;
        }
    }

    /**
     * @param map the keymap values
     */
    public static void initialise(Hashtable map) {
        _map = map;
    }

    /**
     * @return true if the map is not null and not empty
     */
    public static boolean isInitialised() {
        return _map != null && !_map.isEmpty();
    }
}
